import json
from itertools import product as itertools_product
import time
from handle.S2Redis import redis_client, sync_data_background
from object.models import Logisticsvendors,Logistics,Logisticstrack
from object.database import db
from handle.logger import logger
from config import Config
import random
import datetime


# Function to generate random time updates
def generate_random_time(base_time, num_updates):
    updates = []
    for _ in range(num_updates):
        base_time += datetime.timedelta(minutes=random.randint(10, 180))
        updates.append(base_time.strftime("%Y-%m-%d %H:%M:%S"))
    return updates

# Sample logistics data messages
messages = [
    "快件已揽收", "快件已装车", "快件运输中", "快件已到达中转站", "快件正在派送", 
    "快件已签收", "快件已入库", "快件已出库", "快件延误，请耐心等待", "快件到达目的地城市"
]

# Generate 20 sets of logistics node information
logistics_data = []
base_time = datetime.datetime.now()


def fake_node():
    num_nodes = random.randint(2, 6)  # Each set has 2 to 6 nodes
    timestamps = generate_random_time(base_time, num_nodes)
    return json.dumps([{"update_time": timestamps[i], "data": random.choice(messages)} for i in range(num_nodes)],ensure_ascii=False,sort_keys=False)

def create_new_logistics(request_data):
    # LogisticsID = db.Column('LogisticsID', db.Integer, primary_key=True, autoincrement=True)
    # VendorID = db.Column('VendorID', db.Integer, nullable=False)
    # OrderID = db.Column('OrderID', db.Integer, nullable=False)
    # Address = db.Column('Address', db.String(255),nullable=False)
    # Consignee = db.Column('Consignee', db.String(255),nullable=False)
    # Telephone = db.Column('Telephone', db.String(255),nullable=False)
    # Status = db.Column('Status', db.String(20), nullable=False)
    # Remarks = db.Column('Remarks', db.Text, nullable=True)
    try:
        logistics = Logistics(
            LogisticsID=int(time.time())+int(request_data['VendorID'])+int(request_data['logistics_order_id']),
            VendorID=int(request_data['VendorID']),
            OrderID=request_data['logistics_order_id'],
            Address=request_data['Address'],
            Consignee=request_data['Consignee'],
            Telephone=request_data['Telephone'],
            Status="待揽收",
            Remarks=request_data['Remarks']
        )
        db.session.add(logistics)
        db.session.commit()
        
        logisticstrack=Logisticstrack(
            LogisticsID=logistics.LogisticsID,
            Node=fake_node()
        )
        db.session.add(logisticstrack)
        db.session.commit()
        
        logistics.Status=json.loads(logisticstrack.Node)[-1]['data']
        db.session.commit()
        request_data['LogisticsID']= logistics.LogisticsID
        sync_data_background()
        return request_data
    except Exception as e:
        db.session.rollback()  # 回滚事务
        logger.error(f"处理订单时发生错误：{e}")
        raise
    

def update_new_logistics(request_data):
    try:
        logistics=Logistics.query.filter_by(LogisticsID=request_data['LogisticsID']).all()[0]
        logistics.Address=request_data['Address']
        logistics.Consignee=request_data['Consignee']
        logistics.Telephone=request_data['Telephone']
        logistics.Remarks=request_data['Remarks']
        db.session.commit()
        sync_data_background()
        return request_data
    except Exception as e:
        db.session.rollback()  # 回滚事务
        logger.error(f"处理订单时发生错误：{e}")
        raise
    
def get_logistics_list():
    return json.loads(redis_client.get('logistics'))

def get_logistics_byid(logistics_order_id):
    Logisticstrack_list=json.loads(redis_client.get("logisticstrack"))
    for logisticstrack in Logisticstrack_list:
        if int(logisticstrack['LogisticsID'])==int(logistics_order_id):
            logisticstrack['Node']=json.loads(logisticstrack['Node'])
            logger.error(logisticstrack)
            return logisticstrack
    return {"error": "未找到该物流信息"}
 
 
def del_logistics(logistics_order_id):
    try:
        logistics=Logistics.query.filter_by(LogisticsID=logistics_order_id).all()[0]
        db.session.delete(logistics)
        db.session.commit()
        sync_data_background()
    except Exception as e:
        db.session.rollback()  # 回滚事务
        logger.error(f"处理订单时发生错误：{e}")
        raise